import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@SpringBootTest
public class DynamicThreadPool {

    private ThreadPoolExecutor threadPool;
    private int corePoolSize;

    public DynamicThreadPool(int initialCorePoolSize, int maxPoolSize, long keepAliveTime, TimeUnit unit,
                             BlockingQueue<Runnable> workQueue) {
        this.corePoolSize = initialCorePoolSize;
        this.threadPool = new ThreadPoolExecutor(
                initialCorePoolSize, maxPoolSize, keepAliveTime, unit, workQueue,
                new ThreadPoolExecutor.AbortPolicy()
        );
        scheduleCoreThreadAdjustment();
    }

    private void scheduleCoreThreadAdjustment() {
        ScheduledExecutorService adjustmentScheduler = Executors.newScheduledThreadPool(1);
        adjustmentScheduler.scheduleAtFixedRate(this::adjustCoreThreads, 5, 5, TimeUnit.SECONDS);
    }

    private void adjustCoreThreads() {
        int queueSize = threadPool.getQueue().size();
        int currentCorePoolSize = threadPool.getCorePoolSize();

        if (queueSize == 0 && currentCorePoolSize < threadPool.getMaximumPoolSize()) { // 等待队列为空且核心线程数未达到最大值
            threadPool.setCorePoolSize(corePoolSize + 1);
            corePoolSize++;
            System.out.println("增加核心线程数到 " + corePoolSize);
        } else if (queueSize >= threadPool.getMaximumPoolSize() - currentCorePoolSize) { // 等待队列接近满且核心线程数大于初始值
            threadPool.setCorePoolSize(Math.max(corePoolSize - 1, 1)); // 保证核心线程数至少为1
            corePoolSize--;
            System.out.println("减少核心线程数到 " + corePoolSize);
        }
    }

    // 示例：提交任务到线程池
    public void submitTask(Runnable task) {
        threadPool.submit(task);
    }

    // 示例：关闭线程池
    public void shutdown() {
        threadPool.shutdown();
    }
}